package com.taplinker.client.db.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.taplinker.client.db.ConversationDBHelper;
import com.taplinker.client.db.bean.Message;
import com.taplinker.core.Resource;
import com.taplinker.core.ResourceManager;

public class MessageDAO implements Resource{
	private static final String DB_MESSAGE_TABLE = "message";
	private SQLiteDatabase mDataBase;
	
	private static MessageDAO instance = new MessageDAO();
	
	private MessageDAO() {
	}
	
	public static MessageDAO getInstance() {
		if (instance != null) return instance;
		synchronized (MessageDAO.class) {
			if (instance == null) {
				instance = new MessageDAO();
				ResourceManager.getInstance().addResource(instance);
			}
		}
		return instance;
	}
	
	public void getDB(Context context) {
		ConversationDBHelper db = new ConversationDBHelper(context, DB_MESSAGE_TABLE, null, 1);
	    mDataBase = db.getWritableDatabase();
	}
	
	public void insert(Context context, Message message) {
		if(mDataBase == null) {
			getDB(context);
		}
		mDataBase.insert(DB_MESSAGE_TABLE, null, message.convert2ContentValues());
	}
	
	public int update(Context context, Message message) {
		if(mDataBase == null) {
			getDB(context);
		}
		return mDataBase.update(DB_MESSAGE_TABLE,
				message.convert2ContentValues(),
				Message.MESSAGE_ID + " = ?",
				new String[]{message.getMessageId()});
	}
	
	private void closeDB() {
		if(mDataBase != null) {
			mDataBase.close();
			mDataBase = null;
		}
	}

	@Override
	public void releaseResource() {
		closeDB();
	}

	@Override
	public void clear() {
		
	}
	
}
